from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from rest_framework.parsers import JSONParser
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from rest_framework import status
from .models import CrawlerTask
from .serializers import CrawlerTaskSerializer


# Create your views here.

# @csrf_exempt
@api_view(['GET', 'POST'])
def crawler_task_list(request):
    if request.method == 'GET':
        # 获取所有数据步骤： 1.获取数据 2.序列化 3.用json格式发送数据
        qs = CrawlerTask.objects.all()
        serilizer = CrawlerTaskSerializer(qs, many=True)
        print(serilizer.data)
        return JsonResponse(serilizer.data, safe=False)
    elif request.method == 'POST':
        # 新增一条数据的步骤： 1.获取数据 2.反序列化 3.保存至数据库 4.发送结果
        data = JSONParser().parse(request)
        serilizer = CrawlerTaskSerializer(data=data)
        if serilizer.is_valid():
            serilizer.save()
            return JsonResponse(serilizer.data, status=status.HTTP_201_CREATED)
        return JsonResponse(serilizer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET'])
def crawler_get_quantity(request, pk):
    if request.method == 'GET':
        qs = CrawlerTask.objects.get_queryset()[:pk]
        serializer = CrawlerTaskSerializer(qs, many=True)
        return JsonResponse(serializer.data, safe=False)


def crawler_task_detail(request, pk):
    # retrieve, update or delete a row of student model

    # 读取单条数据
    try:
        row = CrawlerTask.objects.get(pk=pk)
    except CrawlerTask.DoesNotExist:
        return HttpResponse(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = CrawlerTaskSerializer(row)
        return JsonResponse(serializer.data)
    elif request.method == 'PUT':
        input_data = JSONParser().parse(request)
        serializer = CrawlerTaskSerializer(row, data=input_data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=status.HTTP_200_OK)
    elif request.method == 'DELETE':
        row.delete()
        return HttpResponse(status=status.HTTP_204_NO_CONTENT)


from django.shortcuts import render

# Create your views here.
